package com.example.gymmanagement.handler;

import com.alibaba.fastjson.JSON;
import com.example.gymmanagement.Utils.Result;
import com.example.gymmanagement.Utils.StatusCode;
import com.example.gymmanagement.domain.User;
import com.example.gymmanagement.service.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginIntercepter implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    //在执行controller方法（handler）之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求的接口路径是否为controller方法
        if (!(handler instanceof HandlerMethod)){
            //访问静态资源，放行
            return true;
        }
        //判断token是否为空，及验证token
        String token = request.getHeader("Authorization");
        if (token==null||token==""){
            Result result = new Result(StatusCode.LOGIN_ERR,"未登录");
            response.setContentType("applicaiton/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        User user = loginService.checkToken(token);
        if (user==null){
            Result result = new Result(StatusCode.LOGIN_ERR,"未登录");
            response.setContentType("applicaiton/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //验证成功放行请求
        return true;
    }



}
